#include "detector.h"

Detector::Detector()
{

}

Detector::Detector(const std::string& filename)
{
    addCascade(filename);
}

void Detector::addCascade(const std::string& filename)
{
    cascades.push_back(cv::CascadeClassifier(filename));
}

void Detector::setScale(double value)
{
	mutex.lock();
    scale = value;
	mutex.unlock();
}

double Detector::getScale()
{
	return scale;
}

void Detector::detect(const cv::Mat& image,\
                      std::vector<cv::Rect>& objects)
{
    if(!cascades.empty()) {
		mutex.lock();
        cv::Mat smallImg(cvRound(image.rows/scale),\
                         cvRound(image.cols/scale), CV_8UC1);;
		mutex.unlock();

        if(image.type() != CV_8UC1) {
            cv::Mat grayImg;
            cv::cvtColor(image, grayImg, CV_BGR2GRAY);
            cv::resize(grayImg, smallImg, smallImg.size());
        } else {
            cv::resize(image, smallImg, smallImg.size());
        }

        for(std::vector<cv::CascadeClassifier>::iterator it=cascades.begin(); it!=cascades.end(); ++it) {
            std::vector<cv::Rect> tmp;
            it->detectMultiScale(smallImg, tmp);
            objects.insert(objects.end(), tmp.begin(), tmp.end());
        }

        for(std::vector<cv::Rect>::iterator\
            it=objects.begin(); it!=objects.end(); ++it) {
            it->x *= scale;
            it->y *= scale;
            it->width *= scale;
            it->height *= scale;
        }
    }
}
